//
//  LoginCodeView.swift
//  GoCash
//
//  Created by jie on 2024/5/13.
//

import SwiftUI

struct LoginCodeView: View {
    
    @Binding var phone: String
    @State var codeButtonDisable = false
    
    @State var codeString = ""
    @FocusState private var isFocused: Bool
    
    @State var timerCount: Int = 60
    @State var voiceTimerCount: Int = -1
    
    func getCode(index: Int) -> String {
        if index > codeString.count { return "" }
        return (codeString as NSString).substring(with: NSMakeRange(index-1, 1))
    }
    
    var body: some View {
        VStack(spacing: 0) {
            Text("El código de verificación ha sido enviado a ")
                .font(Font.system(size: 24, weight: .bold))
                .foregroundColor(COLOR_312A31)
                .padding(.top, 60)
            
            HStack {
                Text("+52 \(phone)")
                    .font(Font.system(size: 20, weight: .medium))
                    .foregroundColor(MAIN_COLOR)
                Spacer()
                
                Button(action: {
                    timerCount = 60
                    codeButtonDisable = true
                   Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { t in
                       self.timerCount = timerCount - 1
                        if timerCount < 0 {
                            codeButtonDisable = false
                            t.invalidate()
                        }
                    }
                }, label: {
                    Text(codeButtonString())
                        .font(Font.system(size: 12))
                        .foregroundColor(.white)
                        .frame(width: 64, height: 24)
                        .background(!codeButtonDisable ? MAIN_COLOR:Color(hex: 0xD2CCDA))
                        .cornerRadius(8)
                })
                .disabled(codeButtonDisable)
                
            }.padding(.top, 20)
            
            TextField("", text: $codeString)
                .padding(0)
                .focused($isFocused)
                .keyboardType(.numberPad)
                .opacity(0)
                .onChange(of: codeString) { value in
                    if value.count >= 4 {
                        AppDelegate.closeKeyboard()
                        codeInputDone()
                    }
                }
            
                .padding(0)
            
            HStack(spacing: 16) {
                CodeItemView(str: Binding.constant(getCode(index: 1)), onTapGesture: codeItemTap)
                CodeItemView(str: Binding.constant(getCode(index: 2)), onTapGesture: codeItemTap)
                CodeItemView(str: Binding.constant(getCode(index: 3)), onTapGesture: codeItemTap)
                CodeItemView(str: Binding.constant(getCode(index: 4)), onTapGesture: codeItemTap)
            }.padding(.top, 30)
            

            VoiceCodeView(count: .constant(voiceTimerCount)) {
                voiceTimerCount = 60
               Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { t in
                   voiceTimerCount = voiceTimerCount - 1
                    if voiceTimerCount < 0 {
                        t.invalidate()
                    }
                }
            }
            
            Spacer()
        }.padding(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
        
            .navigationBarBackButtonHidden()
            .navigationBarItems(
                leading: NagigationBackButton(whiteStyle: true),
                trailing: NagigationServiceButton()
            )
            .onAppear() {
                sendCode()
            }
            .navigationBarUIColor(.clear)
    }
    
    func codeInputDone() {
        AppState.shared.mainPageState = 1
    }
    
    func sendCode() {}
    
    func codeButtonString() -> String {
        if codeButtonDisable == false {
            return "Reenviar"
        } else {
            return "\(timerCount)s"
        }
    }
    
    func codeItemTap() {
        if codeString.count == 4 { codeString = "" }
        isFocused = true
    }
}

#Preview {
    LoginCodeView(phone: Binding.constant("12345678543"))
}


struct CodeItemView: View {
    
    @Binding var str: String
    
    var onTapGesture: ()->Void
    
    var body: some View {
        let width = (SCREEN_WIDHT - 16*5)/4.0
        ZStack {
            Rectangle()
                .frame(height: width)
                .foregroundColor(MAIN_COLOR.opacity(str.count==0 ? 0.1:0.5)).opacity(0.1)
                .cornerRadius(8)
                .overlay(
                    RoundedRectangle(cornerRadius: 8, style: .continuous)
                        .stroke(MAIN_COLOR.opacity(str.count==0 ? 0.1:0.4), lineWidth: 2)
                    
                )
                .onTapGesture {
                    onTapGesture()
                }
            Text(str)
                .foregroundColor(MAIN_COLOR)
                .font(Font.system(size: 32, weight: .bold))
        }
    }
}


struct VoiceCodeView: View {
    
    @Binding var count: Int
    var onTapGesture: ()->Void
    
    var body: some View {
        HStack {
            Spacer()
            if count < 0 {
                Text("¿No recibió el mensaje?")
                    .font(Font.system(size: 12, weight: .regular))
                    .foregroundColor(COLOR_A57AA5)
                
                Text(" Enviar el código de voz")
                    .font(Font.system(size: 12, weight: .regular))
                    .foregroundColor(MAIN_COLOR)
                    .underline(color: MAIN_COLOR)
                    .onTapGesture{ onTapGesture() }
                    .disabled(count >= 0 ? true : false)
            } else {
                Text("Código de voz enviado (\(count)s)")
                    .font(Font.system(size: 12, weight: .regular))
                    .foregroundColor(MAIN_COLOR).opacity(0.5)
            }
            
        }.padding(.top, 20)
    }
}
